import { saveArticle, getArticleDetail } from '../services/article';
import { message } from 'antd';
import { routerRedux } from 'dva/router';

var init = true;
export default {

    namespace: 'article',

    state: {
        postloading: false,
        title: '',
        content: ''
    },

    subscriptions: {
        setup({ history, dispatch }) {
            // 监听 history 变化，当进入 `/` 时触发 `load` action
            return history.listen(({ pathname }) => {
                if (pathname.indexOf('articledetail') > -1) {
                    var arr = pathname.split('/');
                    var param = arr[arr.length - 1];
                    dispatch({ type: 'getArticleDetail', payload: { ArticleFindID: param } });
                }
            });

        },
    },

    effects: {
        *go({ payload }, { call, put }) {
            yield put(routerRedux.push(payload.url));
        },
        *saveArticle({ payload }, { call, put }) {
            yield put({ type: 'showloading' });
            const result = yield call(saveArticle, payload);
            yield put({ type: 'hideloading' });
            const { data } = result;
            if (data.success) {
                message.success(data.message);
                yield put(routerRedux.push('/articledetail/' + data.data));
            }
            else {
                message.error(data.message);
            }

        },
        *getArticleDetail({ payload }, { call, put, select }) {
            //const todos = yield select(state => state.todos);
            const result = yield call(getArticleDetail, payload);
            const { data } = result;
            if (data.success) {
                yield put({ type: 'setdetail', payload: data.data });
            }
            else {
                message.error('初始化失败！');
            }
        }
    },

    reducers: {
        showloading(state) {
            return { ...state, postloading: true };
        },
        hideloading(state) {
            return { ...state, postloading: false };
        },
        setdetail(state, { payload }) {
            return { ...state, title: payload.title, content: payload.content }
        }
    },

};

